package net.qiyuesuo.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import net.qiyuesuo.dao.FileMetaDao;
import net.qiyuesuo.dao.config.ConnectionManager;
import net.qiyuesuo.pojo.FileMeta;
import net.qiyuesuo.utils.SqlUtils;

public class FileMetaDaoImpl implements FileMetaDao{
	
	@Override
	public FileMeta getByKey(String key) {
		String sql = SqlUtils.getInfoSql(key);
		FileMeta meta = null;
		
		try (Connection conn = ConnectionManager.getConnection();
				PreparedStatement pst = conn.prepareStatement(sql);
				ResultSet rs =  pst.executeQuery();){
			String fileKey = null;
			long size = 0;
			Date createTime = null;
			while (rs.next()) {
				fileKey = rs.getString("fileKey");
				size = rs.getLong("size");
				createTime = rs.getDate("createTime");
			}
			meta = new FileMeta(fileKey, size, createTime);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return meta;
	}

	@Override
	public int delete(String key) {
		String sql = SqlUtils.getDeleteSql(key);
		int result = 0;
		Connection conn = ConnectionManager.getConnection();
		try(PreparedStatement pst = conn.prepareStatement(sql)) {
			result = pst.executeUpdate();
			conn.commit();
		} catch (SQLException e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public int insert(FileMeta fileMeta) {
		String sql = SqlUtils.getInsertSql();
		int result = 0;
		Connection conn = ConnectionManager.getConnection();
		try (PreparedStatement pst = conn.prepareStatement(sql);){
			pst.setString(1, fileMeta.getUuid());
			pst.setLong(2, fileMeta.getSize());
			pst.setDate(3, new java.sql.Date(fileMeta.getCreateTime().getTime()));
			result = pst.executeUpdate();
			conn.commit();
		} catch (SQLException e1) {
				try {
					conn.rollback();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			e1.printStackTrace();
		}
		return result;
	}

	@Override
	public int update(FileMeta fileMeta) {
		String sql = SqlUtils.getUpdateSql();
		int result = 0;
		Connection conn = ConnectionManager.getConnection();
		try (PreparedStatement pst = conn.prepareStatement(sql);){
			pst.setLong(1, fileMeta.getSize());
			pst.setDate(2, new java.sql.Date(fileMeta.getCreateTime().getTime()));
			pst.setString(3, fileMeta.getUuid());
			result = pst.executeUpdate();
			conn.commit();
		} catch (SQLException e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
		return result;
	}
	
}
